package leetcode.median;

public class $794_ValidTicTacToe {
    public boolean validTicTacToe(String[] board) {
        int xCount = 0;
        int oCount = 0;
        for (String s:board) {
            for (char c : s.toCharArray()) {
                if (c == 'X') {
                    xCount++;
                } else if (c == 'O') {
                    oCount++;
                }
            }
        }
        if (oCount > xCount || xCount - oCount > 1) {
            return false;
        }

        if (isWin(board, 'X') && xCount != oCount + 1) {
            return false;
        }

        if (isWin(board, 'O') && xCount != oCount) {
            return false;
        }
        return true;
    }

    public boolean isWin(String[] board, char c) {
        for (int i = 0;i < 3;i++) {
            // 同一行
            if (board[i].charAt(0) == c && board[i].charAt(1) == c && board[i].charAt(2) == c) {
                return true;
            }
            // 同一列
            if (board[0].charAt(i) == c && board[1].charAt(i) == c && board[2].charAt(i) == c) {
                return true;
            }
        }
        // 对角线 从左到右
        if (board[0].charAt(0) == c && board[1].charAt(1) == c && board[2].charAt(2) == c) {
            return true;
        }
        // 对角线 从右到左
        if (board[0].charAt(2) == c && board[1].charAt(1) == c && board[2].charAt(0) == c) {
            return true;
        }
        return false;
    }
}
